﻿using CPPEI.Coolzon.Common;
using CPPEI.Coolzon.ServiceProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace CPPEI.Coolzon.Designer.Views
{
    /// <summary>
    /// Interaction logic for DataSourcePreview.xaml
    /// </summary>
    public partial class DataSourcePreview : Window
    {
        public DataSourcePreview()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Event.NCL.NCLEventBus.Register(this);
            LoadDataSource();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Event.NCL.NCLEventBus.Unregister(this);
        }

        private void LoadDataSource()
        {
            SetEnable(false);
            _ctltbDataSource.Visibility = Visibility.Visible;
            _ctlRetry.Visibility = Visibility.Collapsed;
            _ctlDataSource.Visibility = Visibility.Collapsed;
            if (UIContext.Current.CurrentSolution == null)
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSourceListEvent(UIContext.Current.Token, Guid.Empty));
            }
            else
            {
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSourceListEvent(UIContext.Current.Token, UIContext.Current.CurrentSolution.ID));
            }
        }
        [Subscribe]
        public void EndGetDataSourceList(Event.NCL.EndGetDataSourceListEvent @event)
        {
            SetEnable(true);
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
                Dispatcher.Invoke(() =>
                {
                    _ctltbDataSource.Visibility = Visibility.Collapsed;
                    _ctlRetry.Visibility = Visibility.Visible;
                    _ctlDataSource.Visibility = Visibility.Collapsed;
                });
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                if (@event.DataSources != null)
                {
                    Dispatcher.Invoke(() =>
                    {
                        _ctltbDataSource.Visibility = Visibility.Collapsed;
                        _ctlRetry.Visibility = Visibility.Collapsed;
                        _ctlDataSource.Visibility = Visibility.Visible;
                        _ctlDataSource.ItemsSource = @event.DataSources;
                    });
                }
            }
        }

        private void _ctlDataSource_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (_ctlDataSource.SelectedItem != null)
            {
                _ctlDataSet.ItemsSource = null;
                CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSource selectedDataSource = _ctlDataSource.SelectedItem as CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSource;
                Event.NCL.NCLEventBus.Publish(new Event.NCL.BeginGetDataSetListEvent(UIContext.Current.Token, selectedDataSource.Id));
            }
        }
        [Subscribe]
        public void EndGetDataSetList(Event.NCL.EndGetDataSetListEvent @event)
        {
            if (@event.State == Event.NCL.NCLEventState.Failure)
            {
            }
            else if (@event.State == Event.NCL.NCLEventState.Finished)
            {
                if (@event.DataSets != null && @event.DataSets.Length > 0)
                {
                    Dispatcher.Invoke(() =>
                    {
                        _ctlDataSet.ItemsSource = @event.DataSets;
                    });
                }
            }
        }

        private void _ctlDataSet_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _ctlParams.Children.Clear();
            _ctlParams.RowDefinitions.Clear();
            if (_ctlDataSet.SelectedItem != null)
            {
                CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSet selectedDataSet = _ctlDataSet.SelectedItem as CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSet;
                if (selectedDataSet.Parameters != null && selectedDataSet.Parameters.Length > 0)
                {
                    int row = 0;
                    foreach (var item in selectedDataSet.Parameters)
                    {
                        _ctlParams.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
                        TextBlock tb = new TextBlock();
                        tb.Text = item.Name;
                        tb.ToolTip = item.Caption;
                        tb.Margin = new Thickness(3, 5, 3, 3);
                        TextBox tbox = new TextBox();
                        tbox.Tag = item;
                        tbox.Margin = new Thickness(3);
                        Grid.SetColumn(tb, 0);
                        Grid.SetColumn(tbox, 1);
                        Grid.SetRow(tb, row);
                        Grid.SetRow(tbox, row);
                        _ctlParams.Children.Add(tb);
                        _ctlParams.Children.Add(tbox);
                        row++;
                    }
                }
                else
                {
                    TextBlock tb = new TextBlock();
                    tb.Text = "无参数";
                    tb.Margin = new Thickness(3, 5, 3, 3);
                    _ctlParams.Children.Add(tb);
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (_ctlDataSource.SelectedItem == null)
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("请选择数据源", "");
                return;
            }
            if (_ctlDataSet.SelectedItem == null)
            {
                Coolzon.UI.CustomMessageBox.ShowWarning("请选择数据集", "");
                return;
            }

            string dataSource = (_ctlDataSource.SelectedItem as CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSource).Name;
            string dataSet = (_ctlDataSet.SelectedItem as CPPEI.Coolzon.ServiceProxy.DesignServiceRef.DataSet).Name;
            ServiceProxy.DataServiceRef.DataParameter[] Parameters = GetParameters().ToArray();
            ServiceProxy.DataServiceRef.DataResult dataResult = DataServiceProxyManager.Create().GetData(UIContext.Current.Token, dataSource, dataSet, Parameters);
            if (dataResult != null)
            {
                List<DataSourcePreviewModel> dataList = new List<DataSourcePreviewModel>();
                foreach(var dataSeries in dataResult.DataSeries)
                {
                    foreach(var item in dataSeries.DataItems)
                    {
                        DataSourcePreviewModel newModel = new DataSourcePreviewModel();
                        newModel.SeriesID = dataSeries.Id;
                        newModel.SeriesName = dataSeries.Name;
                        newModel.ItemID = item.Id;
                        newModel.ItemName = item.Name;
                        newModel.Value = item.Value;

                        dataList.Add(newModel);
                    }
                }
                _ctlDataGrid.ItemsSource = dataList;
            }
            else
            {
                _ctlDataGrid.ItemsSource = null;
            }
        }
        private List<ServiceProxy.DataServiceRef.DataParameter> GetParameters()
        {
            List<ServiceProxy.DataServiceRef.DataParameter> dataParameterList = new List<ServiceProxy.DataServiceRef.DataParameter>();
            if (_ctlParams.Children != null && _ctlParams.Children.Count > 0)
            {
                foreach (var item in _ctlParams.Children)
                {
                    if (item is TextBox)
                    {
                        TextBox tbox = item as TextBox;
                        ServiceProxy.DesignServiceRef.DataParameter designDataParameter = tbox.Tag as ServiceProxy.DesignServiceRef.DataParameter;

                        ServiceProxy.DataServiceRef.DataParameter dataParameter = new ServiceProxy.DataServiceRef.DataParameter();
                        dataParameter.Name = designDataParameter.Name;
                        dataParameter.Type = designDataParameter.Type;
                        dataParameter.ValueString = tbox.Text;

                        dataParameterList.Add(dataParameter);
                    }
                }
            }
            return dataParameterList;
        }

        private void SetEnable(bool isEnable)
        {
            Dispatcher.Invoke(() =>
            {
                _ctlDataSource.IsEnabled = IsEnabled;
                _ctlDataSet.IsEnabled = isEnable;
                _ctlParams.IsEnabled = isEnable;
                _ctlSP.IsEnabled = isEnable;
            });
        }

        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            LoadDataSource();
        }
    }
}
